package com.hc.session.controller;

import cn.hutool.core.util.ArrayUtil;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author: huangcheng
 * @CreateTime: 2023-09-14  17:38
 * @Description:
 * @Version: 1.0
 */
@RestController
public class SessionController {

    @GetMapping("/set")
    public String set(HttpServletRequest request, HttpServletResponse response){
        //服务端保存session
        HttpSession session = request.getSession();
        session.setAttribute("sessionkey","sessionValue");
        //客户端保存cookie
        Cookie cookie = new Cookie("cookieKey","cookieValue");
        response.addCookie(cookie);
        return "测试";
    }

    @GetMapping("/get")
    public String get(HttpServletRequest request){
        //服务端获取session数据
        HttpSession session = request.getSession();
        Object sessionValue = session.getAttribute("sessionkey");
        System.out.println("session保存的值: "+sessionValue);
        String jsSessionId = session.getId();
        System.out.println("jsSessionId: "+jsSessionId);
        System.out.println(session.getAttribute(jsSessionId));
        //获取cookie数据
        Cookie[] cookies =  request.getCookies();
        if(ArrayUtil.isNotEmpty(cookies)){
            for(Cookie cookie : cookies){
                System.out.println("cookieName: "+cookie.getName());
                System.out.println("cookieValue: "+cookie.getValue());
            }
        }
        return null;
    }

}
